<template>
  <el-dialog
    class="public-dialog"
    :title="`${isEdit ? '修改' : '新增'}`"
    width="630"
    :modelValue="modelValue"
    @close="handleClose"
    draggable
    align-center
    destroy-on-close
  >
    <div :class="props.type === 'postCode' ? 'h-[680px]' : 'h-[300px]'">
      <el-form
        label-position="top"
        ref="formRef"
        :model="formValues"
        :rules="rules"
      >
        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item
              label="区域名称"
              prop="region_id"
              v-if="props.type !== 'postCode'"
            >
              <el-select
                v-model="formValues.region_id"
                placeholder="请选择"
                class="w-full"
                filterable
                clearable
              >
                <el-option
                  v-for="item in optionsData?.mapRegion || []"
                  :key="item"
                  :label="item.region_name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="区域名称" v-else>
              <el-input
                v-model="formValues.region_name"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <div class="flex justify-between">
              <el-form-item label="区域国家" prop="country">
                <el-select
                  v-model="formValues.country"
                  placeholder="请选择"
                  filterable
                  clearable
                  :multiple="props.type !== 'postCode'"
                  collapse-tags
                  collapse-tags-tooltip
                  class="select-wrapper-style"
                >
                  <el-option
                    v-for="item in optionsData?.country || []"
                    :key="item"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item
                label="是否FBA仓点"
                prop="is_fba_warehouse"
                v-if="props.type == 'postCode'"
              >
                <el-switch v-model="formValues.is_fba_warehouse" />
              </el-form-item>
            </div>
          </el-col>
        </el-row>
        <el-form-item label="匹配类型" v-if="props.type === 'postCode'">
          <el-radio-group v-model="formValues.match_type">
            <el-radio
              :label="item.value"
              v-for="item in optionsData?.zip_code_match || []"
              :key="item"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
          <div class="text-[#a8abb2] text-[12px]">
            正向匹配逻辑:先匹配精确,在匹配精确和分段,最后匹配前缀;
          </div>
        </el-form-item>
        <el-form-item label="按精确邮编和城市" v-if="props.type === 'postCode'">
          <template #label>
            <div class="flex justify-between">
              <div>按精确邮编和城市</div>
              <div>
                <el-button
                  type="primary"
                  link
                  @click="formValues.precise_code = null"
                >
                  清空
                </el-button>
              </div>
            </div>
          </template>
          <el-input
            v-model="formValues.precise_code"
            type="textarea"
            :autosize="{ minRows: 4, maxRows: 6 }"
            @blur="OnPreciseBlur"
            placeholder="只能维护精准邮编城市，多个请换行维护！ 样例：88766&city，即精准邮编为88766的邮编，和对应的城市"
          ></el-input>
          <div
            class="text-[#a8abb2] text-[12px] w-[100%] flex leading-[16px] mt-[4px]"
          >
            只能维护精准邮编城市，多个请换行维护！
            样例：88766&city，即精准邮编为88766的邮编，和对应的城市!
          </div>
        </el-form-item>
        <el-form-item label="按分段邮编" v-if="props.type === 'postCode'">
          <template #label>
            <div class="flex justify-between">
              <div>按分段邮编</div>
              <div>
                <el-button
                  type="primary"
                  link
                  @click="formValues.sub_code = null"
                >
                  清空
                </el-button>
              </div>
            </div>
          </template>
          <el-input
            v-model="formValues.sub_code"
            type="textarea"
            :autosize="{ minRows: 4, maxRows: 6 }"
            placeholder="只能维护范围邮编，存在多个范围请换行维护！ 样例：99111-99220，即在前5位在此段范围的邮编；"
          ></el-input>
        </el-form-item>
        <el-form-item label="按前缀邮编" v-if="props.type === 'postCode'">
          <template #label>
            <div class="flex justify-between">
              <div>按前缀邮编</div>
              <div>
                <el-button
                  type="primary"
                  link
                  @click="formValues.prefix_code = null"
                >
                  清空
                </el-button>
              </div>
            </div>
          </template>
          <el-input
            v-model="formValues.prefix_code"
            type="textarea"
            :autosize="{ minRows: 4, maxRows: 6 }"
            @blur="OnPrefixBlur"
            placeholder="每个邮编只允许维护一行,多个请换行维护! 样例:887,即邮编首3位为887的邮编"
          ></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="formValues.remark"
            type="textarea"
            :autosize="{ minRows: 4, maxRows: 8 }"
            placeholder="请输入备注"
          ></el-input>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-button">
        <el-button :disabled="loading" @click="handleClose(false)">
          {{ disabled ? "关闭" : "取消" }}
        </el-button>
        <el-button
          v-if="!disabled"
          type="primary"
          :loading="loading"
          @click="handleSave"
        >
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="jsx">
import { ElMessage } from "element-plus";
import {
  createCountry,
  updateCountry,
  countryDetail,
  createZipCode,
  updateZipCode,
  zipCodeDetail,
} from "../api";

const props = defineProps({
  id: { type: [String, Number], default: "" },
  modelValue: { type: Boolean, default: false },
  disabled: { type: Boolean, default: false },
  type: { type: String, default: "postCode" },
  optionsData: { type: Object, default: () => {} },
});

const emit = defineEmits(["update:modelValue", "refresh", "close"]);

const formValues = ref({});

const rules = {
  region_id: [{ required: true, message: "请选择区域名称", trigger: "blur" }],
  country: [{ required: true, message: "请选择区域国家", trigger: "blur" }],
  region_name: [{ required: true, message: "请输入区域名称", trigger: "blur" }],
};
const model = ref({});
const loading = ref();
const formRef = ref();

const OnPreciseBlur = () => {
  let precise = formValues.value?.precise_code?.replace(/\t/g, "&");
  formValues.value.precise_cod = precise;
};
const OnPrefixBlur = async () => {
  let prefix = formValues.value?.prefix_code?.replace(/\t/g, "&");
  formValues.value.prefix_code = prefix;
};

watch(
  () => props.id,
  (val) => {
    if (val) {
      nextTick(() => {
        getDetail(val);
      });
    }
  }
);

const getDetail = async (id) => {
  try {
    const _api = {
      country: countryDetail,
      postCode: zipCodeDetail,
    };
    const { type } = props;
    const { data } = await _api[type]({ id });

    const { sub_code, precise_code, prefix_code, is_fba_warehouse } = data;
    const postCodeData = {
      sub_code: sub_code?.length ? sub_code.join("\n") : null,
      precise_code: precise_code?.length ? precise_code.join("\n") : null,
      prefix_code: prefix_code?.length ? prefix_code.join("\n") : null,
      is_fba_warehouse: Boolean(is_fba_warehouse),
    };
    formValues.value = Object.assign(
      {
        ...data,
      },
      postCodeData
    );
  } catch (e) {
    console.error(e);
  }
};

const isEdit = computed(() => {
  return !!props.id;
});

const handleSave = async () => {
  if (!await formRef.value?.validate()) return
  try {
    const api = {
      country: {
        edit: updateCountry,
        add: createCountry,
      },
      postCode: {
        edit: updateZipCode,
        add: createZipCode,
      },
    };
    const { id, type } = props;

    const { sub_code, precise_code, prefix_code, is_fba_warehouse } =
      formValues.value;
    const postCodeParams = {
      sub_code:
        sub_code && sub_code.toString()?.trim?.().length
          ? sub_code.split("\n")
          : undefined,
      precise_code:
        precise_code && precise_code.toString()?.trim?.().length
          ? precise_code?.replace(/\t/g, "&")?.split("\n")
          : undefined,
      prefix_code:
        prefix_code && prefix_code.toString()?.trim?.().length
          ? prefix_code?.replace(/\t/g, "&")?.split("\n")
          : undefined,
      is_fba_warehouse: +is_fba_warehouse,
    };
    const reqParams = Object.assign(
      {
        id: id || undefined,
        ...formValues.value,
      },
      type === "postCode" ? postCodeParams : null
    );
    const { code, message } = await api[type][isEdit.value ? "edit" : "add"](
      reqParams
    );
    if (code !== 200) {
      ElMessage.warning(message);
      return;
    }
    ElMessage.success(isEdit.value ? "修改成功" : "保存成功");
    handleClose(true);
  } catch (e) {
    if (e.toString().includes(false)) {
      ElMessage.warning("请检查表单信息");
    }
    console.error(e);
  } finally {
    loading.value = false;
  }
};

const handleClose = async (refresh) => {
  formValues.value = {};
  await nextTick();
  formRef.value.resetFields();
  emit("update:modelValue", false);
  emit("close");
  if (refresh) emit("refresh");
};
</script>
